import { forwardRef, useImperativeHandle, useState } from 'react'
import { Form, Input, Cascader, DatePicker, Select, Radio } from 'antd'
import { ModelTable } from '@/components/other/modelTable'
import { dearleColumns } from './data'
import { getUserlistApi } from '@/api/tom'

const FormConfig = forwardRef(({ orginList = [], productList = [] }, ref) => {
    const [form] = Form.useForm()
    const [isAllSelected, setIsAllSelected] = useState(false)

    useImperativeHandle(ref, () => ({
        setFieldsValue: form.setFieldsValue,
        submit: () => form.validateFields(),
        reset: () => form.resetFields(),
    }))

    function handleProductChange(value: string[]) {
        if (value.includes('all')) {
            form.setFieldsValue({ product: ['all'] })
            setIsAllSelected(true)
            return
        }
        setIsAllSelected(false)
    }
    const dateFormat = 'YYYY/MM/DD'
    const disabledDate = (current: any) => {
        // 只能选择今天及之后的日期
        return current && current < Date.now() - 86400000
    }
    function handleSelect(rows: any[]) {
        form.setFieldsValue({ chooseDealer: rows })
    }
    return (
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={{ dealer: 1 }}
            autoComplete="off" // 关闭自动完成功能，避免浏览器自动填充  
            layout="horizontal"
        >
            <Form.Item
                label="申报单位"
                name="orgin"
                rules={[{ required: true, message: '请选择申报单位' }]}
            >
                <Cascader options={orginList} />
            </Form.Item>

            <Form.Item
                label="申报截止日期"
                name="date"
                rules={[{ required: true, message: '请选择申报截止日期' }]}
            >
                <DatePicker format={dateFormat} disabledDate={disabledDate} />
            </Form.Item>

            <Form.Item
                label="申报产品"
                name="product"
                rules={[{ required: true, message: '请选择申报产品' }]}
            >
                <Select
                    mode="multiple"
                    allowClear
                    style={{ width: '100%' }}
                    placeholder="请选择申报产品"
                    options={productList.map((item) => ({
                        ...item,
                        disabled:
                            item.value !== 'all' && isAllSelected
                                ? true
                                : item.disabled,
                    }))}
                    onChange={handleProductChange}
                />
            </Form.Item>
            <Form.Item
                label="申报对象"
                name="dealer"
                rules={[{ required: true, message: '请选择经销商' }]}
            >
                <Radio.Group>
                    <Radio value={1}>全部经销商</Radio>
                    <Radio value={2}>指定经销商</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(prev, cur) => prev.dealer !== cur.dealer}
            >
                {({ getFieldValue }) =>
                    getFieldValue('dealer') === 2 ? (
                        <Form.Item
                            label="选择经销商"
                            name="chooseDealer"
                            rules={[
                                { required: true, message: '请选择经销商' },
                            ]}
                        >
                            {/* ✅ 再包一层，拿到当前 chooseDealer 值 */}
                            <Form.Item noStyle dependencies={['chooseDealer']}>
                                {({ getFieldValue }) => (
                                    <ModelTable
                                        title="选择经销商"
                                        Columns={dearleColumns}
                                        Api={getUserlistApi}
                                        rowkey="id"
                                        rowName="username"
                                        handleSelect={handleSelect}
                                        // ✅ 把当前表单中的值传给 ModelTable
                                        initialRows={getFieldValue(
                                            'chooseDealer'
                                        )}
                                    />
                                )}
                            </Form.Item>
                        </Form.Item>
                    ) : null
                }
            </Form.Item>
            <Form.Item label=" " colon={false}>
                <p>
                    注意： 1.同一申报单位、同一产品，只能有一条审核中的申报记录
                </p>
                <p>1.已核销数据，不会重复申报</p>
                <p>2.上次核销结余数量会加入到本次申报统计中</p>
            </Form.Item>
            <Form.Item label="id" name="id" hidden={true}>
                <Input />
            </Form.Item>
        </Form>
    )
})

export default FormConfig
